package com.dodo.blog.ui.ajax;

import com.dodo.blog.RequestCycle;
import com.dodo.blog.ui.ajax.annotation.AjaxRequest;
import com.dodo.blog.ui.page.Page;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

/**
 * @author <a href="mailto:pohorelec@comvai.com">Jozef Pohorelec</a>
 */
public class AjaxRequestHandler
        extends AbstractAjaxRequestHandler
{
    private static final long serialVersionUID = 1L;

    @Override
    public void handle() throws Exception
    {
        HttpServletRequest httpRequest = RequestCycle.get().getRequest();
        HttpServletResponse httpResponse = RequestCycle.get().getResponse();

        String paramMethod = httpRequest.getParameter( AjaxListenerHelper.PARAM_METHOD );
        if ( paramMethod != null )
        {
            Page page = RequestCycle.get().getInjector().getInstance( getPageClass() );
            for ( Method method : page.getClass().getDeclaredMethods() )
            {
                AjaxRequest ajaxRequestAnnotation = method.getAnnotation( AjaxRequest.class );
                if ( ajaxRequestAnnotation != null && ajaxRequestAnnotation.name().equals( paramMethod ) )
                {
                    try
                    {
                        Response response = ( Response ) method.invoke( page );
                        response.setMessages( RequestCycle.get().getMessages() );
                        httpResponse.getWriter().write( MAPPER.writeValueAsString( response ) );
                    }
                    catch ( InvocationTargetException e )
                    {
                        throw ( Exception ) e.getCause();
                    }
                    return;
                }
            }

            log.severe( "No method with annotation " + AjaxRequest.class.getName() + "(name = '" + paramMethod + "') found in class " + page.getClass().getName() );
        }
    }
}
